package com.example.springsecurity.common.filter.handle;

import cn.hutool.json.JSONUtil;
import com.example.springsecurity.common.resp.ResponseResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

import static com.example.springsecurity.common.enums.GlobalExceptionEnum.ERROR_SERVER_USER_PERMISSIONS_FAIL;

/**
 * @Description：当访问接口没有权限时，自定义的返回结果
 * @Author：fengcheng
 * @Date：2025/1/17 10:51
 */
@Component
public class RestfulAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(JSONUtil.parse(ResponseResult.forbidden(ERROR_SERVER_USER_PERMISSIONS_FAIL.getMessage())));
        response.getWriter().flush();
    }
}
